const express = require("express");
const router = express.Router();
const { IMAGES_PATH, md5 } = require('../../tools/helper')
const fs = require('fs');
const path = require('path');
const os = require('os');
const useCommonFun = require('../common')

// 打印HTML
router.get("/:filename(*)", async (req, res) => {
    const { filename } = req.params;
    const ossProcess = req.query['x-oss-process']; //例：image/resize,h_300,w_300
    const filePath = path.join(IMAGES_PATH, filename);
    // 检查目录是否存在
    if (!fs.existsSync(filePath)) {
        const dir = path.dirname(filePath);
        if (!fs.existsSync(dir)) {
            fs.mkdirSync(dir, { recursive: true });
        }
        let image = 'https://pic.yzhfuture.com/' + filename
        await useCommonFun.downloadByUrl(filePath, image)
    }
    try {
        const buffer = os.arch() == 'x64' ? await x64(filePath, ossProcess) : await x32(filePath, ossProcess);
        console.log("os.arch()",os.arch())
        res.set('Cache-Control', 'public, max-age=3600');
        res.set('Content-Type', 'image/png');
        res.send(buffer);
    } catch (err) {
        res.status(500).send('Image processing failed');
    }
});


async function x32(filePath, ossProcess) {
    const Jimp = require('jimp');
    let image = await Jimp.read(filePath);
    // 解析 x-oss-process
    if (ossProcess && ossProcess.startsWith('image/resize')) {
        const [, paramsStr] = ossProcess.split('resize,');
        const params = paramsStr.split(',').reduce((acc, part) => {
            const [key, value] = part.split('_');
            acc[key] = parseInt(value, 10);
            return acc;
        }, {});
        const width = params.w || null;
        const height = params.h || null;
        if (width || height) {
            image = image.resize(width || Jimp.AUTO, height || Jimp.AUTO);
        }
    }
    const mime = Jimp.MIME_JPEG;
    const buffer = await image.getBufferAsync(mime);
    return buffer
}

async function x64(filePath, ossProcess) {
    const sharp = require('sharp');
    let image = sharp(filePath);
    console.log("filePath",filePath)
    // 解析 x-oss-process
    if (ossProcess && ossProcess.startsWith('image/resize')) {
        const [, paramsStr] = ossProcess.split('resize,');
        const params = paramsStr.split(',').reduce((acc, part) => {
            const [key, value] = part.split('_');
            acc[key] = parseInt(value, 10);
            return acc;
        }, {});
        const width = params.w || null;
        const height = params.h || null;
        image = image.resize(width, height);
    }
    const buffer = await image.toBuffer();
    return buffer
}


module.exports = router;